//
//  SearchViewController.m
//  AmazingShopping
//
//  Created by Tan on 4/6/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchResultCell.h"
#import "ProductDetailViewController.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

@synthesize searchBar, tableView, titleView, keywordLabel, statusSearchLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
    [self initNavigatorBar];
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [self searchMoreProduct];
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setSearchBar:nil];
    [self setTableView:nil];
    [self setBackButtonView:nil];
    [self setTitleView:nil];
    [self setKeywordLabel:nil];
    [self setStatusSearchLabel:nil];
    [super viewDidUnload];
}

-(void)viewWillAppear:(BOOL)animated{
    if (!isFromSearchResult || isFromHome) {
        [self loadSearchBar];
        isFromSearchResult = NO;
    }else{
        [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    }
}

- (void)loadSearchBar{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    tableView.hidden = YES;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    CGRect frame = searchBar.frame;
    frame.origin.y = 0;
    searchBar.frame = frame;
    frame = tableView.frame;
    frame.origin.y = searchBar.frame.size.height;
    tableView.frame = frame;
    [searchBar becomeFirstResponder];
    
    [UIView commitAnimations];
}

- (void)unloadSearchBar{
    [self.searchBar resignFirstResponder];
    CGRect frame = searchBar.frame;
    frame.origin.y = 0 - searchBar.frame.size.height;
    searchBar.frame = frame;
    
    frame = tableView.frame;
    frame.origin.y = 0;
    tableView.frame = frame;
    tableView.hidden = NO;
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)initNavigatorBar{
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithCustomView:self.backButtonView];
    self.navigationItem.leftBarButtonItem = backButton;
    backButton = nil;
    
    self.navigationItem.titleView = titleView;
}

- (IBAction)backButtonPressed:(id)sender {
    [self loadSearchBar];
}

- (void)searchMoreProduct{
    int offset = [productArray count];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/search_product", serverPath]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request addPostValue: [NSString stringWithFormat:@"%@", self.searchBar.text] forKey:@"key_word"];
    [request addPostValue: [NSString stringWithFormat:@"%d", offset] forKey:@"offset"];
    [request setDelegate:self];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSData *responseData = [request responseData];
        JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
        NSArray *result = [jsonDecoder objectWithData:responseData];
        if (result != NULL) {
            NSArray *moreProduct = [result valueForKey:@"productArray"];
            NSLog(@"%@", moreProduct);
            NSMutableArray *indexPathArray = [[NSMutableArray alloc]init];
            for (int i = 0; i < moreProduct.count; i++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(offset + i) inSection:0];
                [indexPathArray addObject:indexPath];
            }
            int64_t delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.tableView beginUpdates];
                [productArray addObjectsFromArray:moreProduct];
                [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView endUpdates];
                [self.tableView.infiniteScrollingView stopAnimating];
            });
        }else{
           
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"No Data";
//            label.text = @"No Data";
            [self.tableView.infiniteScrollingView setCustomView:label forState:SVInfiniteScrollingStateStopped];
             [self.tableView.infiniteScrollingView stopAnimating];
            NSLog(@"No Data");
        }
    }else{
        NSLog(@"Something's wrong");
    }

}

#pragma mark -
#pragma mark UISearch Bar Delegate
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    if (productArray.count == 0) {
        [self.searchBar resignFirstResponder];
    }else if (!isFromHome){        
        [self unloadSearchBar];
    }else{
        [self.tabBarController setSelectedIndex:0];
        isFromHome = NO;
    }    
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    tableView.hidden = YES;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if ([searchText isEqualToString:@" "]) {
        self.searchBar.text = @"";
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if (![self.searchBar.text isEqualToString:@""]) {
        isFromHome = NO;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/search_product", serverPath]];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request addPostValue: [NSString stringWithFormat:@"%@", self.searchBar.text] forKey:@"key_word"];
        [request addPostValue: [NSString stringWithFormat:@"%d", 0] forKey:@"offset"];
        [request setDelegate:self];
        [self unloadSearchBar];
        statusSearchLabel.text = [NSString stringWithFormat:@"Searching..."];
        keywordLabel.text = [NSString stringWithFormat:@"\"%@\"", self.searchBar.text];
        [request startSynchronous];
        NSError *error = [request error];
        if (!error) {
            NSData *responseData = [request responseData];
            JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
            NSArray *result = [jsonDecoder objectWithData:responseData];
            if (result != NULL) {
                productArray = [[NSMutableArray alloc]initWithArray:[result valueForKey:@"productArray"]];
                [self.tableView reloadData];
                statusSearchLabel.text = [NSString stringWithFormat:@"(%d)",[[result valueForKey:@"count"] integerValue]];
            }else{
                NSLog(@"Not Found");
            }
        }else{
            NSLog(@"Something's wrong");
        }
    }
}

#pragma mark -
#pragma mark Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [productArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = [indexPath row];
    
    //Init cell
    static NSString *SearchResultIdentifier = @"SearchResultIdentifier";
    UINib *nib = [UINib nibWithNibName:@"SearchResultCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:SearchResultIdentifier];
    SearchResultCell *cell = [self.tableView dequeueReusableCellWithIdentifier:SearchResultIdentifier];
        
    //Set cell data
    [cell setProductName: [[productArray objectAtIndex:row] valueForKey:@"product_name"]];
    [cell setPrice: [[productArray objectAtIndex:row] valueForKey:@"product_price"]];
    [cell setSellerName:[[productArray objectAtIndex:row] valueForKey:@"seller_name"]];
    [cell setProductImagePath:[[[productArray objectAtIndex:row] valueForKey:@"product_images"] objectAtIndex:0]];
    [cell setReviewNumber: (NSInteger*)[[[productArray objectAtIndex:row] valueForKey:@"product_review_number"] integerValue]];
    [cell setProductRate: [[[productArray objectAtIndex:row] valueForKey:@"product_review"] floatValue]];
        
    //Set cell style
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

#pragma mark Table View Delegates

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = [indexPath row];
    ProductDetailViewController *nextController = [[ProductDetailViewController alloc]init];
    [nextController setProductID:(NSInteger *)[[[productArray objectAtIndex:row] valueForKey:@"product_id"] integerValue]];
    [self.navigationController pushViewController:nextController animated:YES];
    isFromSearchResult = YES;
    nextController = nil;
}


@end
